<!--外部指标管理-返回码详细-->
<template>
	<div>
		<!-- 搜索表单 -->
		<el-form :model="queryParams" :inline="true" :label-width="100">
			<el-form-item label="返回码名称" prop="name">
				<el-select v-model="queryParams.name" clearable placeholder="请选择返回码名称" @change="returnCodeNameChange">
					<el-option v-for="item in returnCodeNameOptions" :key="item.value" :label="item.name" :value="item.value"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="Search" @click="handlerQuery">查 询</el-button>
			</el-form-item>
		</el-form>
		<!-- 数据列表 -->
		<YdTable
			:formData="queryParams"
			:tableConfig="tableConfig"
			:tableData="tableData.data"
			@sizeChangeHandler="queryList"
			@currentChangeHandler="queryList"
			@sortChangeHandler="queryList"
			@selectionChangeHandler="handlerSelectionChange"
		>
		</YdTable>
		<!-- 新增修改返回码详情 -->
		<el-dialog :title="title" v-model="open" width="600px" append-to-body center>
			<el-form ref="codeForm" :model="form" :rules="rules" label-width="80px">
				<el-form-item label-width="100px" label="返回码名称" prop="nameId">
					<el-select v-model="form.name" placeholder="请选择" readonly :disabled="true">
						<el-option v-for="item in nameOptions" :key="item.id" :label="item.label" :value="item.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label-width="100px" label="类型名称" prop="typeId">
					<el-select v-model="form.typeId" clearable placeholder="请选择">
						<el-option v-for="item in options.typeName" :key="item.code" :label="item.label" :value="item.code"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label-width="100px" label="返回码值" prop="value">
					<el-input v-model="form.value" />
				</el-form-item>
				<el-form-item label-width="100px" label="返回码说明" prop="explain">
					<el-input v-model="form.explain" />
				</el-form-item>
				<el-form-item label-width="100px" label="返回码状态" prop="state">
					<el-select v-model="form.state" clearable placeholder="请选择">
						<el-option v-for="item in options.stateName" :key="item.key" :label="item.value" :value="item.key"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label-width="100px" label="状态级别" prop="level">
					<el-select v-model="form.level" clearable placeholder="请选择">
						<el-option v-for="item in options.levelName" :key="item.code" :label="item.label" :value="item.code"></el-option>
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<el-button type="primary" @click="">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</template>
		</el-dialog>

		<!-- 上传upload -->
		<el-dialog title="返回码配置详细信息表模板导入" v-model="uploadOpen" width="600px" append-to-body center>
			<div style="text-align: center">
				<el-row>
					<el-button size="small" type="primary" @click="handlerDownloadTemplate">下载模板</el-button>
				</el-row>
				<div style="margin-top: 20px">
					<el-upload
						action="#"
						:limit="1"
						:accept="'xlsx,xls'"
						:on-success="handlerSuccess"
						:on-change="fileChange"
						:on-remove="handlerRemove"
						:on-error="handlerError"
						:file-list="fileList"
						:auto-upload="false"
					>
						<el-button size="small" type="primary"> 上传</el-button>
					</el-upload>
				</div>
			</div>
			<template #footer>
				<el-button type="primary" @click="submitUploadForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</template>
		</el-dialog>
	</div>
</template>

<script setup name="OutsideCodeManagementDetails" lang="ts">
import { getList, save, deleteData, getById, getTemplate, upload } from '@/api/admin/indicatorsManage/codeManagementDetail';
import { downloadFromBlob } from '@/utils/common';
import { querySysDictDataByDictType, queryTReturnCodeType } from '@/api/search/searchOptions';
import { computed, getCurrentInstance, reactive, ref, toRefs, watch } from 'vue';

const { proxy }: any = getCurrentInstance();
const props = defineProps({
	name: String,
	nameOptions: Array,
	code: String,
});

const open = ref(false);
const uploadOpen = ref(false);
// 选中数组
const ids = ref([] as any);
// 非单个禁用
const single = ref(true);
// 非多个禁用
const multiple = ref(true);
//弹出层标题
const title = ref('');
// 表单校验
const rules = ref({
	typeId: [{ required: true, message: '类型名称不能为空', trigger: 'blur' }],
	value: [{ required: true, message: '返回码值不能为空', trigger: 'blur' }],
	explain: [{ required: true, message: '返回码说明不能为空', trigger: 'blur' }],
	state: [{ required: true, message: '返回码状态不能为空', trigger: 'blur' }],
	level: [{ required: true, message: '状态级别不能为空', trigger: 'blur' }],
});
// 表单参数
const data = reactive<anyObj>({
	form: {},
});
const { form } = toRefs(data);
// 返回码信息列表配置
let tableConfig = reactive<TableConfigType | any>({
	// remote: getList,
	columns: [
		{
			label: '返回码值',
			prop: 'value',
		},
		{
			label: '返回码说明',
			prop: 'explain',
		},
		{
			label: '返回码状态',
			prop: 'stateName',
		},
		{
			label: '状态级别',
			prop: 'levelName',
		},
	],
	// 工具栏
	toolBar: [
		{ name: '新增', icon: 'yd-icon-plus', permi: ['outside:codeManagementDetails:add'], handler: () => addHandle() },
		{ name: '修改', icon: 'yd-icon-edit', permi: ['outside:codeManagementDetails:edit'], disable: 'single', handler: () => updateHandle() },
		{ name: '删除', icon: 'yd-icon-delete', permi: ['outside:codeManagementDetails:delete'], disable: 'multiple', handler: () => deleteHandle() },
		{ name: '模板导入', icon: 'yd-icon-import', permi: ['outside:codeManagementDetails:import'], handler: () => uploadHandle() },
	],
	// 开启复选框
	enableSelection: true,
	// 开启分页
	pagination: {
		pageNum: 1,
		pageSize: 10,
		total: 0,
	},
	// 加载层
	loading: true,
});
let options = reactive({
	typeName: [] as any,
	stateName: [
		{
			key: 0,
			value: '异常',
		},
		{
			key: 1,
			value: '正常',
		},
	],
	levelName: [] as any,
});
// 未确认列表数据
let tableData = reactive<anyObj>({
	data: [],
	total: 0,
});

//返回码列表查询参数
let queryParams = reactive<any>({
	name: '',
	pageNum: 1,
	pageSize: 10,
});
let returnCodeNameOptions: any = computed(() => props.nameOptions);
let selectRow = reactive({});
const fileList = ref([] as any);
watch(
	() => props.name,
	(newVal) => {
		queryParams.name = newVal;
		queryList();
	},
	{ deep: true, immediate: true }
);

/** 新增返回码详情-获取状态级别下拉框的数据列表 */
function getLevelNameList(dictType: any) {
	querySysDictDataByDictType(dictType).then((response: ApiResponse | any) => {
		options.levelName = response.data;
	});
}
/** 搜索选项-查询表t_return_code_type对应的数据列表 */
function getTypeNameList() {
	queryTReturnCodeType().then((response: ApiResponse | any) => {
		options.typeName = response.data;
	});
}
function returnCodeNameChange(val: string) {
	queryParams.name = val;
	queryList();
}
/** 查询返回码列表 */
function queryList() {
	let res = returnCodeNameOptions.value.filter((item: any) => item.value === queryParams.name);
	let params = {
		...queryParams,
		name: res && res[0].name,
	};
	tableConfig.loading = true;
	getList(params).then((response: ApiResponse | any) => {
		tableData.data = response.data.records;
		tableConfig.pagination.total = response.data.total;
		tableConfig.loading = false;
	});
}
/** 返回码搜索按钮操作 */
function handlerQuery() {
	queryParams.pageNum = 1;
	queryList();
}
/** 新增按钮操作 */
function addHandle() {
	reset();
	form.value.name = queryParams.name;
	title.value = '新增返回码详情';
	open.value = true;
}
/** 修改按钮操作 */
function updateHandle() {
	reset();
	title.value = '编辑返回码详情';
	const id = ids.value;
	getById(id).then((response: ApiResponse | any) => {
		form.value = response.data;
		open.value = true;
	});
}
/** 删除按钮操作 */
function deleteHandle() {
	proxy.$modal
		.confirm('确定删除?', '警告', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			cancelButtonClass: 'confirm-rigth-cancel-button',
			type: 'warning',
		})
		.then(() => {
			deleteData(ids.value).then((res: ApiResponse | any) => {
				if (res.code === 0) {
					proxy.$modal.msgSuccess('删除成功');
					handlerQuery();
				} else {
					proxy.$modal.msgWarning(res.msg);
				}
			});
		})
		.catch(() => {});
}
/** 模板导入 */
function uploadHandle() {
	fileList.value = [];
	uploadOpen.value = true;
}
function handlerDownloadTemplate() {
	// let res = returnCodeNameOptions.value.filter((item: any) => item.value === props.name);
	// let params = {
	// 	...queryParams,
	// 	name: res && res[0].name,
	// };
	getTemplate(queryParams).then((response: ApiResponse | any) => {
		downloadFromBlob(response, '返回码配置详细信息表模板');
	});
}
function fileChange(file: any) {
	fileList.value[0] = file.raw;
}
function handlerRemove() {
	fileList.value = [];
}
function handlerSuccess() {
	proxy.$modal.msgSuccess('上传成功，点击确认导入!');
}
function handlerError() {
	proxy.$modal.msgError('上传失败');
}
/** 导入提交按钮 */
function submitUploadForm() {
	if (fileList.value[0]) {
		let form = new FormData();
		const isLt5M = fileList.value[0].size / 1024 / 1024 < 5;
		if (!isLt5M) {
			proxy.$modal.msgError('文件大小不能超过5M');
		} else {
			form.append('file', fileList.value[0]);
			upload(form).then((rs: ApiResponse | any) => {
				if (rs.code === 0) {
					proxy.$modal.msgSuccess(rs.data);
					handlerQuery();
					uploadOpen.value = false;
				} else {
					proxy.$modal.msgError(rs.msg);
				}
			});
		}
	} else {
		proxy.$modal.msgError('请先上传文件');
	}
}
/** 确认提交按钮 */
function submitForm() {
	proxy.$refs['codeForm'].validate((valid: boolean) => {
		if (valid) {
			save(form.value).then((response: ApiResponse | any) => {
				if (response.code === 0) {
					if (form.value.id !== undefined) {
						proxy.$modal.msgSuccess('修改成功');
					} else {
						proxy.$modal.msgSuccess('新增成功');
					}
					open.value = false;
					queryList();
				} else {
					proxy.$modal.msgError(response.msg);
				}
			});
		}
	});
}
// 取消按钮
function cancel() {
	open.value = false;
	uploadOpen.value = false;
}
function reset() {
	form.value = {};
}
// 多选框选中数据
function handlerSelectionChange(selection: any) {
	ids.value = selection.map((item: any) => item.id);
	single.value = selection.length !== 1;
	multiple.value = !selection.length;
}
// 获取页面下拉框的数据
// getLevelNameList('sys_alarm_threshold_level'); // 状态级别
// getTypeNameList(); // 获取类型名称下拉框数据
</script>
